package com.resource.collect.util;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import org.apache.commons.lang3.StringUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

public class PythonUtil {


    public static JSONArray exec(String fileName, String[] params) {
        String path = findFile(fileName);
        if(StringUtils.isEmpty(path)){
            throw new RuntimeException(fileName + "：python文件不存在");
        }
        Process proc;
        JSONArray array = new JSONArray();
        try {
            List<String> args = new ArrayList<>();
            args.add("python");
            args.add(path);
            for (String param : params) {
                args.add(param);
            }
            proc = Runtime.getRuntime().exec(args.toArray(new String[args.size()]));// 执行py文件
            //用输入输出流来截取结果
            BufferedReader in = new BufferedReader(new InputStreamReader(proc.getInputStream()));
            String line;
            StringBuffer json = new StringBuffer();
            while ((line = in.readLine()) != null) {
                json.append(line);
                if (json.toString().startsWith("{") && json.toString().endsWith("}")) {
                    JSONObject obj = JSONObject.parseObject(json.toString());
                    array.add(obj);
                    json.setLength(0);
                }

            }
            in.close();
            proc.waitFor();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return array;
    }

    public static String findFile(String targetName) {
        String rootPath = System.getProperty("user.dir");
        Path path = Paths.get(rootPath + "/../resource-collect-spider");
        Path file = null;
        try {
            // 获取该路径下的所有文件和文件夹
            file = Files.walk(path)
                    .filter(Files::isRegularFile) // 只处理普通文件，不处理目录
                    .filter(p -> p.getFileName().toString().equals(targetName)) // 过滤出文件名匹配的文件
                    .findFirst()
                    .orElse(null);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return Optional.ofNullable(file).map(f ->f.toAbsolutePath().toString()).orElse("");
    }
}
